import asyncio
import json
import time
from curl_cffi import requests
import subprocess
from functools import partial
import execjs
import hashlib


subprocess.Popen = partial(subprocess.Popen, encoding='utf-8')

# 加载 JS 文件
with open('h5st516.js', 'r', encoding='utf-8') as f:
    js = f.read()

js_com = execjs.compile(js)


cookie={}
def sha_256(message):
    return hashlib.sha256(message.encode('utf-8')).hexdigest()
proxies = {
    "http": "http://127.0.0.1:7890",
    "https": "http://127.0.0.1:7890",
}

def generate_comment_h5st(params):
    """
    生成评论接口的 h5st 参数
    """
    # 解析原始 body
    body_str = params['body']
    body = json.loads(body_str) if isinstance(body_str, str) else body_str

    # 创建用于生成 h5st 的 a 对象
    a = {
        "appid": params.get('appid', 'pc-rate-qa'),
        "body": sha_256(body_str if isinstance(body_str, str) else json.dumps(body, separators=(',', ':'))),
        "clientVersion": params.get('clientVersion', '1.0.0'),
        "client": params.get('client', 'pc'),
        "functionId": params.get('functionId', 'getCommentListPage'),
        "t": int(time.time() * 1000),  # 使用当前时间戳
    }

    # 调用 JS 的 sign 方法生成 h5st
    h5st = js_com.call('getH5st', a)

    return h5st


def get_jd_comments(sku_id, page_num=1, sort_type="5"):
    """
    获取京东商品评论

    Args:
        sku_id: 商品SKU ID
        page_num: 页码
        sort_type: 排序类型 (5: 默认排序)

    Returns:
        评论数据的 JSON 响应
    """

    # 构建请求体
    body = {
        "requestSource": "pc",
        "shopComment": 0,
        "sameComment": 0,
        "channel": None,
        "extInfo": {
            "isQzc": "0",
            "spuId": str(sku_id),
            "commentRate": "1",
            "needTopAlbum": "1",
            "bbtf": "",
            "userGroupComment": "1"
        },
        "num": "10",
        "pictureCommentType": "A",
        "scval": None,
        "shadowMainSku": "0",
        "shopType": "0",
        "firstCommentGuid": "fd82058b687fb3d5b0326fdf2ae5c1a9",
        "sku": str(sku_id),
        "category": "12259;12260;9435",  # 这个可能需要根据实际商品调整
        "shieldCurrentComment": "1",
        "pageSize": "10",
        "isFirstRequest": False,
        "style": "1",
        "isCurrentSku": False,
        "sortType": sort_type,
        "tagId": "",
        "tagType": "",
        "type": "0",
        "pageNum": str(page_num)
    }

    # 准备参数
    timestamp = str(int(time.time() * 1000))
    params = {
        "appid": "pc-rate-qa",
        "functionId": "getCommentListPage",
        "client": "pc",
        "clientVersion": "1.0.0",
        "t": timestamp,
        "body": json.dumps(body, separators=(',', ':')),
        "loginType": "3",
        "uuid": "1744782034530924475269"  # 这个可以动态生成或从cookie中获取
    }

    # 生成 h5st
    h5st = generate_comment_h5st(params)
    params['h5st'] = h5st

    headers = {
        "Host": "api.m.jd.com",
        "pragma": "no-cache",
        "cache-control": "no-cache",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-ch-ua": "\"Chromium\";v=\"136\", \"Microsoft Edge\";v=\"136\", \"Not.A/Brand\";v=\"99\"",
        "sec-ch-ua-mobile": "?0",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0",
        "accept": "application/json, text/plain, */*",
        "x-referer-page": "https://item.jd.com/100008190077.html",
        "content-type": "application/x-www-form-urlencoded",
        "x-rp-client": "h5_1.0.0",
        "origin": "https://item.jd.com",
        "sec-fetch-site": "same-site",
        "sec-fetch-mode": "cors",
        "sec-fetch-dest": "empty",
        "referer": "https://item.jd.com/",
        "accept-language": "zh-CN,zh;q=0.9,ar;q=0.8",
        "priority": "u=1, i"
    }

    # 发送 POST 请求
    url = "https://api.m.jd.com/client.action"

    try:
        response = requests.post(url, headers=headers,data=params,proxies=proxies,cookies=cookies)
        print(response.status_code)
        print(response.json())
        # 保存响应到文件（可选）
        # with open(f"comments_{sku_id}_page{page_num}.json", "w", encoding="utf-8") as f:
        #     f.write(response.text)

        print(f"获取第 {page_num} 页评论成功")
        return response.json()

    except Exception as e:
        print(f"请求失败: {e}")
        return None


# 使用示例
if __name__ == "__main__":
    sku_id = "100008190077"
    all_comments = []

    # 循环获取1~100页评论
    for page in range(1,4):
        print(f"\n正在获取第 {page} 页评论...")
        comments = get_jd_comments(sku_id, page_num=page)
        if comments:
            all_comments.append(comments)  # 或者处理 comments['comments'] 这样的字段
        else:
            print(f"第 {page} 页获取失败，跳过。")

        # 可适当加个sleep防止过快被限制
        time.sleep(5)

    # 保存所有结果到文件
    with open(f"comments_{sku_id}_pages1-100.json", "w", encoding="utf-8") as f:
        json.dump(all_comments, f, ensure_ascii=False, indent=2)

    print("所有页码评论抓取完成！")
